package hy.iot.core.support;

import hy.iot.core.handler.Handler;
import hy.iot.core.handler.SchemaHandler;
import hy.iot.core.schema.IotSchema;
import hy.iot.core.utils.ClassUtils;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ParserSupport {

    // 默认解析器
    private static String defaultSchema;
    //自定义解析器
    private static String customSchema;

    private static Class<IotSchema> IotschemaClass = IotSchema.class;

    private static Map<String, Handler> customizeSchemaMap;

    public ParserSupport(String defaultSchema, String customSchema) {
        this.defaultSchema = defaultSchema;
        this.customSchema = customSchema;
        this.customizeSchemaMap = new HashMap<String,Handler>();
    }

    public Map<String, Handler> getSchemas() {
        // 扫描包路径 拿到所有的解析器
        if (StringUtils.isNotBlank(defaultSchema)){
            List<Class> defaultSchemaList =  ClassUtils.getInterFaceImplList(defaultSchema, IotschemaClass);
            handlerSchema(defaultSchemaList);
        }
        if (StringUtils.isNotBlank(customSchema)){
            List<Class> customSchemaList =  ClassUtils.getInterFaceImplList(customSchema, IotschemaClass);
            handlerSchema(customSchemaList);
        }
        return customizeSchemaMap;
    }

    private void handlerSchema(List<Class> defaultSchemaList) {
        if (defaultSchemaList != null) {
            for (Class clazz : defaultSchemaList) {
                try {
                    if (IotschemaClass.isAssignableFrom(clazz)){
                        Method[] methods = clazz.getDeclaredMethods();
                        for (Method method : methods) {
                            if (method.getName().equals("handleByte")){
                                Handler handler = new SchemaHandler(clazz.newInstance(),method,clazz.getSimpleName(), false);
                                customizeSchemaMap.put(clazz.getSimpleName(), handler);
                            }
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException("custom schema fail class:" + clazz.getSimpleName(), e);
                }
            }
        }
    }


}
